import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mvvm_provider/page/novel/states/novel_detail_state.dart';
import 'package:mvvm_provider/page/novel/view_model/novel_detail_view_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../base/base_stateful_page.dart';
import '../../../base/consumer_widget.dart';
import '../widgets/novel_content_item.dart';

class NovelDetailPage extends BasePage {
  const NovelDetailPage({super.key});

  @override
  BasePageState<BasePage> getState() => _NovelDetailPageState();
}

class _NovelDetailPageState extends BasePageState<NovelDetailPage> {
  // NovelDetailViewModel novelDetailViewModel = NovelDetailViewModel();

  bool bCanPress = true;
  @override
  void initState() {
    super.initState();
    super.pageTitle = '详情';
    getListData();
  }

  void getListData() {
    getViewModel<NovelDetailViewModel>().getTabsData();
    getViewModel<NovelDetailViewModel>().getContentData();
  }

  /// 上拉加载
  void _onLoading() {
    getViewModel<NovelDetailViewModel>()
        .changeIndex(getViewModel<NovelDetailViewModel>().state.selectIndex + 1);
  }

  /// 下拉刷新
  void _onRefresh() {
    getViewModel<NovelDetailViewModel>()
        .changeIndex(getViewModel<NovelDetailViewModel>().state.selectIndex - 1);
  }

  Widget _tabsWidget() {
    return Container(
      width: 1.sw / 4,
      color: const Color(0xF3F4F8FF),
      child: ListView.builder(
        cacheExtent: 20,
        physics: const BouncingScrollPhysics(),
        reverse: false,
        itemCount: getViewModel<NovelDetailViewModel>().state.tabsList.length,
        itemBuilder: (context, index) {
          return InkWell(
            child: Container(
              alignment: Alignment.center,
              width: 1.sw / 4,
              height: 50.h,
              decoration: BoxDecoration(
                  color: getViewModel<NovelDetailViewModel>().state.selectIndex != index
                      ? const Color(0xF3F4F8FF)
                      : Colors.white),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  getViewModel<NovelDetailViewModel>().state.selectIndex == index
                      ? Container(
                          padding: EdgeInsets.only(bottom: 10.h, top: 10.h),
                          width: 4.w,
                          height: 30.h,
                          decoration: BoxDecoration(
                              color: Colors.lightBlue, borderRadius: BorderRadius.circular(4.h)))
                      : const SizedBox(),
                  AnimatedDefaultTextStyle(
                    duration: const Duration(milliseconds: 200),
                    style: TextStyle(
                        fontSize: getViewModel<NovelDetailViewModel>().state.selectIndex != index
                            ? 12.sp
                            : 16.sp,
                        color: Colors.black),
                    child: Text(
                      getViewModel<NovelDetailViewModel>().state.tabsList[index].name,
                    ),
                  ),
                  const SizedBox()
                ],
              ),
            ),
            onTap: () {
              getViewModel<NovelDetailViewModel>().changeIndex(index);
            },
          );
        },
      ),
    );
  }

  Widget _contentWidget() {
    return RefreshConfiguration(
      headerTriggerDistance: 10,
      footerTriggerDistance: 1,
      enableBallisticLoad: false,
      headerBuilder: () => const RefreshCustomHeader(),
      footerBuilder: () => const LoadingCustomFooter(),
      child: Container(
        width: 1.sw / 4 * 3,
        color: Colors.white,
        child: SmartRefresher(
            physics: const BouncingScrollPhysics(),
            enablePullUp: true,
            enablePullDown: true,
            controller: getViewModel<NovelDetailViewModel>().refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              cacheExtent: 20,
              physics: const BouncingScrollPhysics(),
              reverse: false,
              controller: getViewModel<NovelDetailViewModel>().scrollController,
              itemCount: getViewModel<NovelDetailViewModel>().state.contentList.length,
              itemBuilder: (context, index) {
                return NovelContentItem(
                  index: index + 1,
                  model: getViewModel<NovelDetailViewModel>().state.contentList[index],
                );
              },
            )),
      ),
    );
  }

  @override
  Widget buildPage(BuildContext context) {
    return ConsumerWidget<NovelDetailViewModel, NovelDetailState>(
      builder: (context, state, child) {
        return Row(
          children: [
            _tabsWidget(),
            _contentWidget(),
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

class RefreshCustomHeader extends StatelessWidget {
  const RefreshCustomHeader({Key? key}) : super(key: key);

  ///提示语
  ///
  /// [showText] 提示内容
  Widget _prompt(String showText, bool isShowLoading) {
    return Container(
      margin: EdgeInsets.only(bottom: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            showText,
            style: TextStyle(color: Colors.blue, fontSize: 12.sp),
          ),
          isShowLoading == true
              ? Container(
                  height: 12.w,
                  width: 12.w,
                  margin: EdgeInsets.only(left: 8.w),
                  child: const CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                  ),
                )
              : const SizedBox()
        ],
      ),
    );
  }

  ///提示语和log
  ///
  /// [showText] 提示内容
  Widget _hint(String showText, {bool isShowLoading = false}) {
    return _prompt(showText, isShowLoading);
  }

  ///列表头
  CustomHeader _header() {
    Widget body = _hint("下拉查看上一个榜单");
    return CustomHeader(
      builder: (context, mode) {
        if (mode == RefreshStatus.idle) {
          body = _hint("下拉查看上一个榜单");
        } else if (mode == RefreshStatus.refreshing) {
          body = _hint("正在加载", isShowLoading: true);
        } else if (mode == RefreshStatus.failed) {
          body = _hint("加载失败！");
        } else if (mode == RefreshStatus.canRefresh) {
          body = _hint("松手查看上一个榜单");
        } else if (mode == RefreshStatus.completed) {
          body = _hint("已为您更新最新数据");
        } else {
          body = _hint("加载失败！");
        }
        return body;
      },
    );
  }

  @override
  Widget build(BuildContext context) => _header();
}

class LoadingCustomFooter extends StatelessWidget {
  const LoadingCustomFooter({Key? key}) : super(key: key);

  ///提示语
  ///
  /// [showText] 提示内容
  Widget _prompt(String showText, bool isShowLoading) {
    return Container(
      margin: EdgeInsets.only(bottom: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            showText,
            style: TextStyle(color: Colors.blue, fontSize: 12.sp),
          ),
          isShowLoading == true
              ? Container(
                  height: 12.w,
                  width: 12.w,
                  margin: EdgeInsets.only(left: 8.w),
                  child: const CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                  ),
                )
              : const SizedBox()
        ],
      ),
    );
  }

  ///提示语和log
  ///
  /// [showText] 提示内容
  Widget _hint(String showText, {bool isShowLoading = false}) {
    return _prompt(showText, isShowLoading);
  }

  ///列表头
  CustomFooter _footer() {
    Widget body = _hint("上拉查看下一个榜单");
    return CustomFooter(
      builder: (context, mode) {
        if (mode == LoadStatus.idle) {
          body = _hint("上拉查看下一个榜单");
        } else if (mode == LoadStatus.loading) {
          body = _hint("加载中...", isShowLoading: true);
        } else if (mode == LoadStatus.failed) {
          body = _hint("加载失败");
        } else if (mode == LoadStatus.canLoading) {
          body = _hint("松手查看下一个榜单");
        } else {
          body = _hint("没有更多了～");
        }
        return body;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return _footer();
  }
}
